#!/usr/bin/env python
# encoding: utf-8

from google.appengine.ext import db
from wsgiref.handlers import CGIHandler

import models


def create_cache_page(parent, path, html, type='main', content_type='text/html'):
    page = models.CachedPage(key_name=path, parent=parent)
    page.html = html
    page.type = type
    page.content_type = content_type
    page.put()


def get_cache_page(path):
    cached_page = models.CachedPage.get_by_key_name(path)    
    if cached_page:
        return_cache_page(cached_page)
        return True
    return False


def return_cache_page(page):
    """Renders a cached page"""
    def Do(environ,start_response):
        """"This function is passed to CGIHandler to render the http response."""
        start_response("200 OK",[('Content-type', str(page.content_type) + '; charset=utf-8'),('Cache-Control','no-cache')])
        return [str(page.html)]
    CGIHandler().run(Do)


def delete_cache(post=None, delete_main=True):
    for page in models.CachedPage.all():
        page.delete()

    #    if post:
    #        for page in models.CachedPage.gql('WHERE ANCESTOR IS :1', post): #Post pages
    #            page.delete()
    #        for category in post.categories:  #Category pages
    #            for page in models.CachedPage.gql('WHERE ANCESTOR IS :1', category):
    #                page.delete()
    #    if delete_main:
    #        for page in models.CachedPage.gql('WHERE type=:1', 'main'): #Main
    #            page.delete()

def main():
	pass


if __name__ == '__main__':
	main()

